<template>
  <video ref="videoRef" autoplay muted controls loop />
</template>

<script setup lang="ts">
// import { useVideoStore } from '@/stores/video'
// https://www.npmjs.com/package/rtc-streamer
import { SrsRtcPlayerAsync } from 'rtc-streamer'
import { onBeforeUnmount, onMounted, ref, watch, type Ref } from 'vue'

const props = defineProps<{ url: string }>()

// 播放器 dom 元素
const videoRef: Ref<HTMLVideoElement | undefined> = ref()

// const video = useVideoStore()

// srs 拉流实例
let srs = new SrsRtcPlayerAsync()

// 监听拉流地址变成重新拉流
watch(
  () => props.url,
  () => {
    initPlay()
  }
)

onMounted(() => {
  initPlay()
})

/**
 * 重新推拉流
 */
// const onRefresh = async () => {
//   await video.getWebRTCUrl()
//   initPlay()
// }

/**
 * 拉流
 */
async function initPlay() {
  srs.close()
  srs = new SrsRtcPlayerAsync()
  if (videoRef.value && props.url) {
    videoRef.value.srcObject = srs.stream
    await srs.play(props.url)
    // srs.stream.getTracks().forEach((track) => {
    //   track.onmute = () => {
    //     onRefresh()
    //   }
    //   track.onended = () => {
    //     onRefresh()
    //   }
    // })
  }
}

// 关闭拉流
onBeforeUnmount(() => {
  if (srs) {
    srs.close()
  }
})

defineExpose({
  initPlay
})
</script>
